package com.cr.common.utils.file;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * Base64转MultipartFile格式
 */
public class Base64DecodedMultipartFile implements MultipartFile {
    private final byte[] imgContent;
    private final String header;
    private final String fileName;

    public Base64DecodedMultipartFile(byte[] imgContent, String header, String fileName) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
        this.fileName = fileName;
    }

    @Override
    public String getName() {
        return fileName + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return fileName + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(imgContent);
        }
    }

    /**
     * base64转multipartFile
     **/
    public static MultipartFile base64Convert(String base64, String fileName) {
        String[] split = base64.split(",");
        String header = split[0];
        String base64Data =  split[1];

        Base64.Decoder decoder = Base64.getDecoder();
        byte[] b = decoder.decode(base64Data);
        //取索引为1的元素进行处理
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        // 处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
        return new Base64DecodedMultipartFile(b, header, fileName);
    }
}

